//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package event_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type EventSourceStateInfoDbItem struct {
	EventSourceId   string `bson:"_id"`
	SourceUserCount uint32 `bson:"sourceUserCount"`
	MapUserCount    uint32 `bson:"mapUserCount"`
	UserCountDirty  bool   `bson:"userCountDirty"`
	EventCount      uint32 `bson:"eventCount"`
}

type _EventSourceStateDao struct {
	mc *mongo.Collection
}

func newEventSourceStateDao(db *mongo.Database) (*_EventSourceStateDao, error) {
	mc := db.Collection(db_ns.DB_NS_EVENT + "source_state")
	return &_EventSourceStateDao{mc: mc}, nil
}

func (db *_EventSourceStateDao) Insert(ctx context.Context, dbItem *EventSourceStateInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_EventSourceStateDao) SetUserCountDirty(ctx context.Context, eventSourceId string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": eventSourceId},
		bson.M{"$set": bson.M{"userCountDirty": true}})
	return err
}

func (db *_EventSourceStateDao) UpdateUserCount(ctx context.Context, eventSourceId string, sourceUserCount, mapUserCount uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": eventSourceId},
		bson.M{"$set": bson.M{"sourceUserCount": sourceUserCount, "mapUserCount": mapUserCount, "userCountDirty": false}})
	return err
}

func (db *_EventSourceStateDao) IncEventCount(ctx context.Context, eventSourceId string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": eventSourceId}, bson.M{"$inc": bson.M{"eventCount": 1}})
	return err
}

func (db *_EventSourceStateDao) ListById(ctx context.Context, eventSourceIdList []string) ([]*EventSourceStateInfoDbItem, error) {
	if len(eventSourceIdList) == 0 {
		return []*EventSourceStateInfoDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": eventSourceIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*EventSourceStateInfoDbItem{}
	err = cursor.All(ctx, &retList)
	if err != nil {
		return nil, err
	}
	return retList, nil
}

func (db *_EventSourceStateDao) Get(ctx context.Context, eventSourceId string) (*EventSourceStateInfoDbItem, error) {
	retItem := &EventSourceStateInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": eventSourceId}).Decode(retItem)
	return retItem, err
}
